Graph Representations

PolyU DSAI2201 Lecture 13 2025-11-25

Storing Graphs: List vs. Matrix

The practical application of graph algorithms hinges on how efficiently the structure G=(V,E)G=(V, E) is stored in memory. We primarily utilize two representation methods, tailored for different graph densities:

  1. Adjacency List: An array (indexed by vertex vVv \in V) where each entry points to a linked list (or dynamic array) containing the neighbors of vv. L[v]{u1,u2,,udegree(v)} L[v] \rightarrow \{ u_1, u_2, \dots, u_{\text{degree}(v)} \}
    • Benefit: Space efficient for sparse graphs (mn2m \ll n^2). Fast iteration over neighbors.
  2. Adjacency Matrix: An n×nn \times n Boolean array AA, where A[i][j]=1A[i][j] = 1 if there is an edge (vi,vj)(v_i, v_j), and 00 otherwise.
    • Benefit: Extremely fast O(1)O(1) edge existence lookup. Simple implementation.

Representation Trade-offs

Let n=Vn = |V| and m=Em = |E|. Understanding the computational trade-offs is crucial for algorithm design.

FeatureAdjacency ListAdjacency Matrix
Space ComplexityO(n+m)O(n + m)O(n2)O(n^2)
Check Edge (u,v)(u, v)O(degree(u))O(\text{degree}(u))O(1)O(1)
Iterate Neighbors of uuO(degree(u))O(\text{degree}(u))O(n)O(n)
Best Use CaseSparse Graphs (mn2m \ll n^2)Dense Graphs (mn2m \approx n^2)
📝 Interactive Checkpoint

Consider a network graph GG with V=10,000|V| = 10,000 vertices and E=20,000|E| = 20,000 edges. This graph is highly sparse.

1. Which representation minimizes memory usage for this specific graph?

  • A) Adjacency List
  • B) Adjacency Matrix
  • C) Both use comparable space

2. What is the time complexity to check if an edge (u,v)(u, v) exists using an Adjacency Matrix?

  • A) O(n)O(n)
  • B) O(logn)O(\log n)
  • C) O(1)O(1)
  • D) O(degree(u))O(\text{degree}(u))

Now, consider a dense social network with 1,000 users where nearly everyone is connected to everyone else (mn2m \approx n^2).

3. Which representation's space complexity becomes more acceptable or even preferable?

  • A) Adjacency List
  • B) Adjacency Matrix
  • C) Neither is suitable

4. For finding all friends of a user (iterating neighbors) in a sparse graph, why is an Adjacency List faster?

  • A) It only processes actual neighbors, not all possible vertices.
  • B) It uses less memory, which always makes it faster.
  • C) Matrix lookups are inherently slow.